import cv2
import numpy as np
import os
from skimage import filters
import matplotlib as mpl
import math
mpl.use('tkagg')
import matplotlib.pyplot as plt
def Imgvar(img):                   # 求图像方差
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    dst=cv2.Laplacian(gray,cv2.CV_64F)    #拉普拉斯变换
    imgvar=dst.var()                      #得出方差
    return imgvar
def caltheta(path):
    img=cv2.imread(path)
    imgsize=img.shape[1]
    drawing = np.zeros(img.shape[:], dtype=np.uint8)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    if imgsize<2000 or Imgvar(img)>1000:
        gray=cv2.GaussianBlur(gray,(5,5),5.5)
    thresh = filters.threshold_otsu(gray)
    edges=cv2.Canny(gray,thresh/3,thresh,7)
    lines = cv2.HoughLinesP(edges,2, np.pi /180,int(thresh), minLineLength=imgsize/7, maxLineGap=20)
    arr=[]
    for line in lines:
        x1, y1, x2, y2 = line[0]
        if  (x2-x1)!=0:
            theta=(y1-y2)/(x2-x1)
            if abs(theta)<0.8:
                cv2.line(drawing, (x1, y1), (x2, y2), (0, 255, 0), 1, lineType=cv2.LINE_AA)
                arr.append(theta)
    iwpath=path.replace('.jpg','.png')
    (counts,bins,patch)=plt.hist(arr, 50)
    plt.xlabel('theta')
    plt.xlim(-0.8, 0.8)
    plt.ylabel('Frequency')
    plt.title('theta')
    # plt.show()
    positon=np.argmax(counts)
    return bins[positon],counts[positon]/sum(counts)
def judge(theta,counts):
    if abs(theta)<0.1 and counts>0.4:
        return 1
    else :
        return 0
if __name__=='__main__':
    #img = cv2.imread('C:/Users/DELL/Desktop/shushida0317-198/JPEGImages/gsk00077.jpg')
    path='C:/Users/DELL/Desktop/shushida0317-198/JPEGImages/gsk00139.jpg'
    theta,counts=caltheta(path)
    if judge(theta,counts)==1:
        print("图片水平")
    else :
        print("图片不规则")




